<?
class bjPluginManager{
	const PLUGIN_INSTALL_SUCCESS		= 1;
	const PLUGIN_FATAL_ERROR			= 0;
	const PLUGIN_MISSING_DESCRIPTOR		= -1;
	const PLUGIN_ALREADY_INSTALLED  	= -2;	
	const PLUGIN_CAN_UPGRADE			= -3;
	
	private static $instance;
	
	private function __construct() {
	}
	
	public static function getInstance(){
		if(empty(self::$instance)){
			self::$instance = new bjPluginManager();	
		}
		
		return self::$instance;
	}
		
	/**
	 * Registers a plugin for first time use
	 * @todo Directory tracking, entrypoint
	 */
	public function register(bjPlugin $p){
		//Make sure descriptors are valid
		$descriptors = $p->getPluginDescriptors();
		
		if(empty($descriptors["title"])){
			return array("errorCode" => self::PLUGIN_MISSING_DESCRIPTOR, "msg" => "Missing title descriptor.");	
		}

		if(empty($descriptors["guid"])){
			return array("errorCode" => self::PLUGIN_MISSING_DESCRIPTOR, "msg" => "Missing guid.");	
		}

		if(empty($descriptors["type"])){
			return array("errorCode" => self::PLUGIN_MISSING_DESCRIPTOR, "msg" => "Missing plugin type.");	
		}
		
		//Check that the plugin does not already exist
		$q = Doctrine_Query::create()
			->select("p.version, p.guid")
    		->from('bjPlugin p')
			->where("p.guid = ?", $p->pluginDescriptors["guid"])
			->setHydrationMode(Doctrine::HYDRATE_ARRAY)
			->fetchOne();
		
		if(!empty($q)){ //Plugin exists, is it an upgrade?
			if($q["version"] != $descriptors["version"]){
				return array("errorCode" => self::PLUGIN_CAN_UPGRADE, "msg" => "This plugin can be upgraded.");	
			}
			
			//Not an upgrade, maybe reinstall?
			return array("errorCode" => self::PLUGIN_ALREADY_INSTALLED, "msg" => "This plugin can be upgraded.");	

		}
		
		//Plugin does not exist in the system, init plugin
		$result = $p->pluginInit();
		
		if($result["errorCode"] > 0){
			//add the plugin to the database
			try{
				$plugin = new bjPlugin();
				$plugin->guid = $descriptors["guid"];
				$plugin->title = $descriptors["title"];
				$plugin->description = $descriptors["description"];
				$plugin->authors = serialize($descriptors["authors"]);
				$plugin->website = $descriptors["website"];
				$plugin->plugin_type = $descriptors["type"];
				$plugin->version = $descriptors["version"];
				$plugin->active = true;
				$plugin->save();

				if($plugin->plugin_id > 0){
					return array("errorCode" => self::PLUGIN_INSTALL_SUCCESS, "msg" => "Plugin installed.");							
				}

				return array("errorCode" => self::PLUGIN_FATAL_ERROR, "msg" => "Error with plugin installation: could not insert into database.");				

			} catch (Exception $e){
				return array("errorCode" => self::PLUGIN_FATAL_ERROR, "msg" => "Error with plugin installation: ".$e->getMessage());				
			}
		} else {
			return array("errorCode" => self::PLUGIN_FATAL_ERROR, "msg" => "Error with plugin installation: ".$result["msg"]);				
		}
		
	}
}

?>